﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace Group_Mail
{
    public partial class frmMain : Form
    {
        private frmConsole console;
        private Thread threadSending;

        public frmMain()
        {
            InitializeComponent();
        }

        private Status CurrentStatus { get; set; }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.mylifevn.com");
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            BindGroups();
            Manager.ThreadComplete += Manager_ThreadComplete;
            ShowConsole();
            console.WriteConsole("Group Mail is startup");
        }

        private void Manager_ThreadComplete(string id, MessageStatus status)
        {
            Manager.UpdateMessage(id, status);
            BindMessages();
        }

        private void btnNewGroup_Click(object sender, EventArgs e)
        {
            try
            {
                var dialog = new frmGroupCreator();
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    var group = dialog.Group;
                    Manager.AddGroup(group);
                    BindGroups();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Group Mail", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnMessages_Click(object sender, EventArgs e)
        {
            BindMessages();
        }

        private void btnGroups_Click(object sender, EventArgs e)
        {
            BindGroups();
        }

        private void BindGroups()
        {
            CurrentStatus = Status.Groups;
            listView.Items.Clear();
            listView.View = View.LargeIcon;
            foreach (var item in Manager.Groups)
            {
                var obj = new ListViewItem(item.Value, 0) {Tag = item.Key};
                listView.Items.Add(obj);
            }
        }

        private void listView_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            if (string.IsNullOrEmpty(e.Label))
            {
                e.CancelEdit = true;
                return;
            }

            switch (CurrentStatus)
            {
                case Status.Groups:
                    var item = listView.Items[e.Item];
                    Manager.RenameGroup(item.Tag.ToString(), e.Label);
                    break;
                case Status.Messages:
                    break;
            }
        }

        private void btnNewAccount_Click(object sender, EventArgs e)
        {
            try
            {
                var dialog = new frmAccountCreator();
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Manager.AddAccount(dialog.Account);
                    BindAccounts();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Group Mail", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BindAccounts()
        {
            CurrentStatus = Status.Accounts;
            listView.Items.Clear();
            listView.View = View.LargeIcon;
            foreach (var item in Manager.Accounts)
            {
                var obj = new ListViewItem(item.Name, 2) {Tag = item.Id};
                listView.Items.Add(obj);
            }
        }

        private void btnAccounts_Click(object sender, EventArgs e)
        {
            BindAccounts();
        }

        private void btnTemplates_Click(object sender, EventArgs e)
        {
            BindTemplates();
        }

        private void BindTemplates()
        {
            CurrentStatus = Status.Templates;
            listView.Items.Clear();
            listView.View = View.LargeIcon;
            foreach (var item in Manager.Templates)
            {
                var obj = new ListViewItem(item.Value, 1) {Tag = item.Key};
                listView.Items.Add(obj);
            }
        }

        private void BindMessages()
        {
            if (InvokeRequired)
            {
                Invoke(new MethodInvoker(BindMessages));
            }
            else
            {
                CurrentStatus = Status.Messages;
                listView.Items.Clear();
                listView.View = View.Details;
                foreach (var item in Manager.Messages)
                {
                    var message = Manager.GetMessageById(item.Key);
                    var accountName = Manager.Accounts.First(a => a.Id == message.AccountId).Name;
                    var groupName = Manager.Groups.First(g => g.Key == message.GroupId).Value;
                    var obj = new ListViewItem(new[] {accountName, groupName, item.Value, message.Status.ToString()}, 1)
                                  {Tag = item.Key};
                    listView.Items.Add(obj);
                }
            }
        }

        private void btnNewTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                var dialog = new frmTemplateCreator();
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Manager.AddTemplate(dialog.Template);
                    BindTemplates();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Group Mail", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void listView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F2 && listView.SelectedItems.Count > 0)
            {
                listView.SelectedItems[0].BeginEdit();
            }
        }

        private void btnNewMessage_Click(object sender, EventArgs e)
        {
            var dialog = new frmMessageCreator();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                Manager.AddMessage(dialog.Message);
                BindMessages();

                if (dialog.Message.Status == MessageStatus.Sending)
                {
                    SendMessage(dialog.Message);
                }
            }
        }

        private void listView_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                switch (CurrentStatus)
                {
                    case Status.Groups:
                        contextMenuGroup.Show(listView, e.Location);
                        break;
                    case Status.Messages:
                        contextMenuMessage.Show(listView, e.Location);
                        break;
                }
            }
        }

        private void btnAddRecipient_Click(object sender, EventArgs e)
        {
            MessageBox.Show("");
        }

        private void btnImportRecipient_Click(object sender, EventArgs e)
        {
            if (listView.SelectedItems.Count > 0)
            {
                var dialog = new frmImportRecipients();
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    var id = listView.SelectedItems[0].Tag.ToString();
                    Manager.AddRecipients(id, dialog.Recipients);
                }
            }
            else
            {
                MessageBox.Show("Please select group for import recipients", "Group Mail");
            }
        }

        private void btnDeleteMessage_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to remove this message?", "Group Mail", MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var id = listView.SelectedItems[0].Tag.ToString();
                Manager.RemoveMessage(id);
                BindMessages();
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            var id = listView.SelectedItems[0].Tag.ToString();
            var message = Manager.GetMessageById(id);
            if (message.Status == MessageStatus.Draft)
            {
                if (threadSending != null && threadSending.IsAlive)
                {
                    MessageBox.Show("Cannot send this message because other message is sending", "Group Mail",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    SendMessage(message);
                }
            }
            else
            {
                MessageBox.Show("Cannot re-send this message", "Group Mail", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }


        private void SendMessage(Message message)
        {
            Manager.MessageSending = message;
            threadSending = new Thread(Manager.SendMessage);
            threadSending.Start();
        }

        private void ShowConsole()
        {
            console = new frmConsole();
            console.Show();
        }

        private void btnConsole_Click(object sender, EventArgs e)
        {
            ShowConsole();
        }

        #region Nested type: Status

        private enum Status
        {
            Groups,
            Messages,
            Accounts,
            Templates,
        }

        #endregion
    }
}